//
//  ViewController.m
//  Lesson_03_CoreData
//
//  Created by xalo on 16/5/28.
//  Copyright © 2016年 蓝鸥科技有限公司西安分公司. All rights reserved.
//

kldjsklfhionfoznhoic

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Teacher.h"
#import "Student.h"
@interface ViewController ()
//关联上下文，一切的增删改查操作由context进行
@property(nonatomic,strong)NSManagedObjectContext *context;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //646adsadadadqwe
    self.context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
    //关联数据库
    //数据库的格式为momd
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc]initWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"Model" withExtension:@"momd"]];
    //通过文件模型去初始化数据持久化处理
    NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
    //创建文件路径
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"modal.sqlite"];
    //关联路径
    //如果支持版本迭代的话那么要在option设置@{NSMigratePersistentStoresAutomaticallyOption:@YES,NSInferMappingModelAutomaticallyOption:@YES}并且要在一开始的时候就需要设置

    [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:filePath] options:@{NSMigratePersistentStoresAutomaticallyOption:@YES,NSInferMappingModelAutomaticallyOption:@YES} error:nil];
    self.context.persistentStoreCoordinator = store;
    NSLog(@"%@",filePath);
    //
}
//添加
- (IBAction)insertAction:(UIButton *)sender {
  //创建一个学生
    Student *stu1 = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];
    stu1.name = @" 国栋";
    stu1.age = @18;
    Student *stu2 = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];
    stu2.name = @"张华";
    stu2.age = @20;
    Student *stu3 = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];
    stu3.name = @"张冲";
    stu3.age = @22;
    Student *stu4 = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];
    stu4.name = @"张恒";
    stu4.age = @26;
    Student *stu5 = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];
    stu5.name = @"张凡";
    stu5.age = @20;

    Teacher *tea = [NSEntityDescription insertNewObjectForEntityForName:@"Teacher" inManagedObjectContext:self.context];
    tea.name = @"Duke";
    tea.course = @"iOS开发";
    tea.myStudent = [NSSet setWithObjects:stu1,stu2,stu3,stu4,stu5, nil];
    [tea addMyStudent:[NSSet setWithObjects:stu1,stu2,stu3,stu4,stu5, nil]];
    //coreData的是用需要注意所有的增删改操作完成之后需要保存一下
    [self.context save:nil];
}
//删除
- (IBAction)deleteAction:(UIButton *)sender {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"国"];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    for (Student *stu in array) {
        [self.context deleteObject:stu];
        [self.context save:nil];
    }
}
//更新
- (IBAction)updataAction:(UIButton *)sender {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",@"张凡"];
    request.predicate = predicate;
    NSArray *array = [self.context executeFetchRequest:request error:nil];
    for (Student *stu in array) {
        //2.修改
        stu.name = @"张展";
        [self.context save:nil];
        
    }
}
//查询
- (IBAction)selectAction:(UIButton *)sender {
////    NSFetchRequest
//    //创建查询学生表请求体
//    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
//    //1.查询年龄为20的人
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age = %@",@18];
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",@"国栋"];
//    //加入谓词条件
//        //执行查询操作
//    //2.查询姓张的人
//    
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"张"];
////    3.查询名字以栋结尾的人
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name LIKE %@",@"*栋"];
//    //4.年龄排序
//    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
//    //加入排序
//    request.sortDescriptors = @[sort];
//    request.predicate = predicate;
//
//   NSArray *array = [self.context executeFetchRequest:request error:nil];
//    for (Student *stu in array) {
//        NSLog(@"%@,%@,%@",stu.name,stu.age,stu.number);
//    }
//    /**
//     *1.创建查询体
//     2.设置查询条件或者排序方式（这一步可有可无，根据需求来决定）
//     2.1查询经常用到的有三种：第一种直接查询[NSPredicate predicateWithFormat:@"name%@",@"张三"]
//                          第二种模糊查[NSPredicate predicateWithFormat:@"name CONTAINS %@",@"张"]
//                          第三种以什么结尾或者以什么开头：[NSPredicate predicateWithFormat:@"name LIKE %@",@"张*"]
//     3.用context去执行查询体并用数组接收
//     **/
//   //查询老师表
//    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Teacher"];
//    NSArray *array = [self.context executeFetchRequest:request error:nil];
//    for (Teacher *tea in array) {
//        for (Student *stu in tea.myStudent) {
//            NSLog(@"%@的学生 %@ %@ %@",tea.name,stu.name,stu.age,stu.number);
//           
//        }
////         NSLog(@"%@",tea.myStudent);
//    }
    
    

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
